package me.hgj.jetpackmvvm.base.activity

import android.app.Activity
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.gyf.immersionbar.ImmersionBar
import com.scwang.smart.refresh.footer.BallPulseFooter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.tamsiree.rxkit.RxActivityTool
import me.hgj.jetpackmvvm.R
import me.hgj.jetpackmvvm.base.UIController
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.databinding.ActivityBaseBinding
import me.hgj.jetpackmvvm.event.EventArgs
import me.hgj.jetpackmvvm.ext.getVmClazz
import me.hgj.jetpackmvvm.network.manager.NetState
import me.hgj.jetpackmvvm.network.manager.NetworkStateManager
import me.hgj.jetpackmvvm.util.DynamicTimeFormat
import java.text.SimpleDateFormat
import java.util.*

/**
 * 作者　: hegaojian
 * 时间　: 2019/12/12
 * 描述　: ViewModelActivity基类，把ViewModel注入进来了
 */
abstract class BaseA<VM : BaseViewModel, VB : ViewBinding> : AppCompatActivity() {

    lateinit var uiShow: UIController

    /**
     * 上下文context
     */
    var baseContext: Activity = FragmentActivity()

    /**
     * 是否需要显示 TipView
     */
    open fun enableNetworkTip(): Boolean = true

    var mImmersionBar: ImmersionBar? = null
    private var imm: InputMethodManager? = null

    var mClassicsHeader: ClassicsHeader? = null

    //    public ClassicsFooter mClassicsFooter;
    var mClassicsFooter: BallPulseFooter? = null

    //    viewmodel  +livedata
    lateinit var mViewModel: VM

    /**
     * ViewBinding
     */
    private var _binding: ViewBinding? = null
    abstract val bindingInflater: (LayoutInflater) -> VB

    @Suppress("UNCHECKED_CAST")
    protected val binding: VB
        get() = _binding as VB

    lateinit var baseBinding: ActivityBaseBinding
    abstract fun initView(savedInstanceState: Bundle?)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        baseContext = this@BaseA
        baseBinding = ActivityBaseBinding.inflate(layoutInflater)
        _binding = bindingInflater.invoke(layoutInflater)
        beforehandInit()
        setContentView(requireNotNull(baseBinding).root)
        init(savedInstanceState)
        initBaseActionEvent()

    }

    private fun init(savedInstanceState: Bundle?) {
        mViewModel = createViewModel()
        initView(savedInstanceState)
        initNetWork()
        initToolBar()
        initImmerBar()
        initSmartRefresh()
        initSmartRefreshValue()
        createObserver()
        NetworkStateManager.instance.mNetworkStateCallback.observeInActivity(this, Observer {
            onNetworkStateChanged(it)
        })
        uiShow = UIController(this)
    }

    abstract fun initNetWork()

    private fun initToolBar() {
        setSupportActionBar(baseBinding.toolbar)
        val actionBar = supportActionBar
        if (actionBar != null) actionBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
//        img_base_back.setOnClickListener(this)

    }

    /**
     * strTitle 标题
     * strRight1  右侧按钮
     */
    fun initTitle(strTitle: String?, strRight1: String? = "") {
        baseBinding.tvBaseTitle.text = strTitle
        if (!TextUtils.isEmpty(strRight1)) {
            baseBinding.tvBaseRight.visibility = View.VISIBLE
            baseBinding.tvBaseRight.text = strRight1
        } else baseBinding.tvBaseRight.visibility = View.GONE
    }

    /**
     *  初始化 状态栏设置
     *  isdark  true  设置状态栏 字体黑色  false  白色
     */
    public fun initImmerBar(isDark: Boolean = true, isSet: Boolean = true) {
        try {
            var currentCls = RxActivityTool.currentActivity()
            if (!isSet) return
        } catch (e: Exception) {
            e.printStackTrace()
        }

        mImmersionBar = ImmersionBar.with(this)
        mImmersionBar?.titleBar(baseBinding.toolbar)?.statusBarDarkFont(isDark, 0.2f)?.init()
    }

    fun initImmKeybord() {
        mImmersionBar?.keyboardEnable(true)?.init()
    }

    /**
     * 初始化之前的一些操作
     */
    private fun beforehandInit() {


    }

    override fun setContentView(view: View?) {
//        baseBinding.root.addView(_binding?.root)
        val ivLeftLayoutParams: ConstraintLayout.LayoutParams = ConstraintLayout.LayoutParams(-1, 0)
        ivLeftLayoutParams.topToBottom = baseBinding.layAppbar.id
        ivLeftLayoutParams.leftToLeft = baseBinding.layRootBase.id
        ivLeftLayoutParams.bottomToBottom = baseBinding.layRootBase.id
        _binding?.root?.rootView?.layoutParams = ivLeftLayoutParams
        baseBinding.layRootBase.addView(_binding?.root?.rootView)
        super.setContentView(baseBinding.layRootBase)

    }

    /**
     * 全局配置
     */
    private fun initBaseActionEvent() {
        mViewModel.getStateInfo().observe(this, Observer {
            when (it.event) {
                EventArgs.SHOW_LOADING -> {
                    showLoading(it.message, it.cancelEnable)
                }
                EventArgs.DO_NOTHING, EventArgs.HIDE_DIALOG -> hideLoading()
                EventArgs.SHOW_ERROR -> {
                    hideLoading()
                    showToast(it.errorMsg)
                }
                EventArgs.SHOW_CONFIRM -> {
                    showConfirmDialog(it.content, true)
                }
                EventArgs.SHOW_TOAST -> {

                    if (it.toastMsg.isNotEmpty()) {
                        showToast(it.toastMsg)
                    } else {
                        showToast(it.message)
                    }
                }
                else -> {

                }
            }
        })
    }


    /**
     * 无网状态—>有网状态 的自动重连操作，子类可重写该方法
     */
    open fun doReConnected() {
        ReGetData()
    }

    /**
     * 开始请求
     */
    open fun ReGetData() {}

    fun setToolbarShow(isShow: Boolean = true) {
        baseBinding.layAppbar.visibility = if (isShow) View.VISIBLE else View.GONE
    }


    /**
     * 网络变化监听 子类重写
     */
    open fun onNetworkStateChanged(netState: NetState) {}

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }

    /**
     * 创建LiveData数据观察者
     */
    open fun createObserver() {}


    //<editor-fold desc="-ui控制">

    fun showConfirmDialog(message: String?, cancelEnable: Boolean) {
        if (this.isDestroyed)
            return
        uiShow?.showConfirmDialog(this, message, cancelEnable)
    }

    fun showToast(message: String?) {
        if (this.isDestroyed)
            return
        uiShow?.showToast(this, message)
    }

    fun showLoading(message: String? = "", cancelEnable: Boolean=false) {
        if (this.isDestroyed)
            return
        uiShow?.showLoading(message.toString(), cancelEnable)
    }

    fun hideLoading() {
        uiShow?.dismissLoading()
    }

    //</editor-fold>
    private fun initSmartRefresh() {

        mClassicsHeader = ClassicsHeader(baseContext)
        //        mClassicsFooter = new ClassicsFooter(baseContext);
        mClassicsFooter = BallPulseFooter(baseContext)
        val deta = Random().nextInt(7 * 24 * 60 * 60 * 1000)
        mClassicsHeader?.setLastUpdateTime(Date(System.currentTimeMillis() - deta))
        mClassicsHeader?.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader?.setTimeFormat(DynamicTimeFormat("更新于 %s"))
        mClassicsHeader?.setEnableLastTime(false)
        mClassicsHeader?.spinnerStyle = SpinnerStyle.Translate
        //        mClassicsHeader.setAccentColor(getResources().getColor(R.color.base_text));//设置强调颜色
        mClassicsHeader?.setPrimaryColor(ContextCompat.getColor(baseContext, R.color.white))//设置主题颜色

        mClassicsFooter?.setAnimatingColor(ContextCompat.getColor(baseContext, R.color.main))//设置
        mClassicsFooter?.setNormalColor(ContextCompat.getColor(baseContext, R.color.blue))//设置 颜色


    }

    private fun initSmartRefreshValue() {
        ClassicsHeader.REFRESH_HEADER_PULLING = getString(R.string.srl_header_pulling);//"下拉可以刷新";
        ClassicsHeader.REFRESH_HEADER_REFRESHING =
            getString(R.string.srl_header_refreshing);//"正在刷新...";
        ClassicsHeader.REFRESH_HEADER_LOADING = getString(R.string.srl_header_loading);//"正在加载...";
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(R.string.srl_header_release);//"释放立即刷新";
        ClassicsHeader.REFRESH_HEADER_FINISH = getString(R.string.srl_header_finish);//"刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = getString(R.string.srl_header_failed);//"刷新失败";
        ClassicsHeader.REFRESH_HEADER_UPDATE =
            getString(R.string.srl_header_update);//"上次更新 M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_UPDATE =
            getString(R.string.srl_header_update);//"'Last update' M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_SECONDARY =
            getString(R.string.srl_header_secondary);//"释放进入二楼"

        ClassicsFooter.REFRESH_FOOTER_PULLING = getString(R.string.srl_footer_pulling);//"上拉加载更多";
        ClassicsFooter.REFRESH_FOOTER_RELEASE = getString(R.string.srl_footer_release);//"释放立即加载";
        ClassicsFooter.REFRESH_FOOTER_LOADING = getString(R.string.srl_footer_loading);//"正在刷新...";
        ClassicsFooter.REFRESH_FOOTER_REFRESHING =
            getString(R.string.srl_footer_refreshing);//"正在加载...";
        ClassicsFooter.REFRESH_FOOTER_FINISH = getString(R.string.srl_footer_finish);//"加载完成";
        ClassicsFooter.REFRESH_FOOTER_FAILED = getString(R.string.srl_footer_failed);//"加载失败";
        ClassicsFooter.REFRESH_FOOTER_NOTHING = getString(R.string.srl_footer_nothing);//"全部加载完成";

    }

    /**
     * 供子类BaseVmDbActivity 初始化Databinding操作
     */
    open fun initDataBind() {}
    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        hideLoading()
    }

}